package uk.dier.account.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import uk.dier.account.dao.ISProductDao;
import uk.dier.account.dto.ProductDto;
import uk.dier.account.entity.Product;
import uk.dier.account.exception.ExceptionDao;
import uk.dier.account.utils.DozerMapper;
import uk.dier.account.utils.HibernateSession;

@Repository
@Transactional
public class ProductDaoImpl extends HibernateSession implements ISProductDao {

	public void saveProduct(Product newProduct) throws ExceptionDao{
		getSession().saveOrUpdate(newProduct);
	}

	public void updateProduct(Product updateProduct) throws ExceptionDao {
		this.saveProduct(updateProduct);
	}

	public void deleteProduct(Product removeProduct) throws ExceptionDao {
		getSession().delete(removeProduct);
	}

	@SuppressWarnings("unchecked")
	public List<ProductDto> findProducttByName(Product product) throws ExceptionDao {
		
		List<ProductDto> listOfProductDto = new ArrayList<ProductDto>();
		// Check name is not empty
		if (StringUtils.hasText(product.getProductName())) {

			// Build HQL
			StringBuilder hql = new StringBuilder();
			hql.append("from Product p ");
			hql.append("where p.productName like '%" + product.getProductName()	+ "%'");

			Query query = getSession().createQuery(hql.toString());
			// Check list is not empty
			if (!query.list().isEmpty()) {
				// Return list of Products
				List<Product> resultProducts = query.list();
				for (Product result : resultProducts) {
					// Map from Products to ProductDto
					listOfProductDto.add(
							DozerMapper.mapClass(result,ProductDto.class));
				}
			}
		}
		return listOfProductDto;
	}

}
